package pingan.com.imandtwo.activity;

import android.Manifest;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import pingan.com.imandtwo.R;
import pingan.com.imandtwo.utils.DensityUtil;

public class PersonalDetailsActivity extends AppCompatActivity implements View.OnClickListener {
    private PopupWindow window;
    private TextView takePhoto, pickPhoto, cancel;
    public static final int TAKE_PHOTO = 1;//拍照
    public static final int CHOOSE_PHOTO = 2;//选择相册
    public static final int PICTURE_CUT = 3;//剪切图片
    private Uri imageUri, outputUri;
    private boolean isClickCamera;//是否是拍照裁剪
    private ImageView mineInfoGoBack;
    private ImageView userimg;
    private TextView username;
    private Bitmap bitmap;
    private final String SDCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    private String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
    private String fileName, imagePath;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.arg1 == 1) {
                et_nick.setText(username.getText());
                et_nick.setSelection(et_nick.getText().length());
            }

            if (msg.arg1 == 2) {
                username.setText(et_nick.getText());
                username.setVisibility(View.VISIBLE);
            }
        }
    };
    private EditText et_nick;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_details);
        mineInfoGoBack = (ImageView) findViewById(R.id.mineInfoGoBack);
        userimg = (ImageView) findViewById(R.id.userimg);
        userimg.setOnClickListener(this);
        username = (TextView) findViewById(R.id.usrenameinfo);
        username.setOnClickListener(this);
        mineInfoGoBack.setOnClickListener(this);
        //判断存放图片的路径文件夹是否存在
        File file = new File(SDCardPath + "/IMandTwo");
        if (!file.exists()) {
            file.mkdir();
            File file1 = new File(SDCardPath + "/IMandTwo/image");
            if (!file1.exists()) {
                file1.mkdir();
            }
        }
    }

    //显示popupWindow
    public void showPop() {
        View winview = View.inflate(this, R.layout.mypop, null);
        int dp = DensityUtil.dip2px(this, 120);
        window = new PopupWindow(winview, ViewGroup.LayoutParams.MATCH_PARENT, dp);
        window.setAnimationStyle(R.style.popup_window_anim);
        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));
        window.setFocusable(true);
        window.setOutsideTouchable(true);
        window.update();
        window.showAsDropDown(getWindow().getDecorView(), 0, -230);
        takePhoto = winview.findViewById(R.id.takePhoto);
        pickPhoto = winview.findViewById(R.id.pickPhoto);
        cancel = winview.findViewById(R.id.cancel);
        takePhoto.setOnClickListener(this);
        pickPhoto.setOnClickListener(this);
        cancel.setOnClickListener(this);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.7f;
        getWindow().setAttributes(lp);
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }
    private void setNickName() {
        et_nick = new EditText(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("修改昵称").setView(et_nick).setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (et_nick.getText().toString().trim().length() >= 1) {
                            ValueAnimator valueAnimator = ValueAnimator.ofInt(et_nick.getLayoutParams().width, 0);
                            valueAnimator.setDuration(500);
                            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                @Override
                                public void onAnimationUpdate(ValueAnimator animator) {

                                    int currentValue = (Integer) animator.getAnimatedValue();
                                    et_nick.getLayoutParams().width = currentValue;
                                    et_nick.requestLayout();
                                }
                            });
                            valueAnimator.start();
                            Message obtain = Message.obtain();
                            obtain.arg1 = 2;
                            handler.sendMessageDelayed(obtain, 500);
                        } else {
                            Toast.makeText(PersonalDetailsActivity.this, "字符不能小于1", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });
        builder.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mineInfoGoBack:
                finish();
                break;
            case R.id.userimg:
                showPop();
                break;
            case R.id.usrenameinfo:
                setNickName();
                break;
            case R.id.takePhoto:
                window.dismiss();
                if (isSupportCamera()) {
                    fileName = SDCardPath + File.separator + "IMandTwo/image/" + name + ".jpg";
                    openCamera();
                } else {
                    Toast.makeText(this, "抱歉，检测不到设备相机", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.pickPhoto:
                window.dismiss();
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    selectFromAlbum();//打开相册
                }
                break;
            case R.id.cancel:
                window.dismiss();
                break;
        }
    }
    public boolean isSupportCamera() {
        PackageManager pm = getPackageManager();
        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)
                && !pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
            return false;
        }
        return true;
    }


    private void openCamera() {
        // 创建File对象，用于存储拍照后的图片
        File outputImage = new File(fileName);
        try {
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT < 24) {
            imageUri = Uri.fromFile(outputImage);
        } else {
            //Android 7.0系统开始 使用本地真实的Uri路径不安全,使用FileProvider封装共享Uri
            //参数二:fileprovider绝对路径 com.dyb.testcamerademo：项目包名
            imageUri = FileProvider.getUriForFile(this, "pingan.com.imandtwo.fileprovider", outputImage);
        }
        // 启动相机程序
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO);
    }


    private void selectFromAlbum() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            openAlbum();
        }
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO); // 打开相册
    }


    /**
     * 裁剪图片
     */
    private void cropPhoto(Uri uri) {
        // 创建File对象，用于存储裁剪后的图片，避免更改原图
        File file = new File(getExternalCacheDir(), "crop_image.jpg");
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        outputUri = Uri.fromFile(file);

        Log.d("zzz",outputUri.toString());
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }

        Log.d("zzz","已经到了");
        intent.setDataAndType(uri, "image/*");
        //裁剪图片的宽高比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("crop", true);//可裁剪
        // 裁剪后输出图片的尺寸大小
        //intent.putExtra("outputX", 400);
        //intent.putExtra("outputY", 200);
        intent.putExtra("scale", true);//支持缩放
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());//输出图片格式
        intent.putExtra("noFaceDetection", true);//取消人脸识别
        Log.d("zzz","阿萨德");
        startActivityForResult(intent, PICTURE_CUT);
    }

    // 4.4及以上系统使用这个方法处理图片 相册图片返回的不再是真实的Uri,而是分装过的Uri
    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        imagePath = null;
        if ( data == null){
            Toast.makeText(this, "未选取到图片", Toast.LENGTH_SHORT).show();
            return ;
        }

        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        cropPhoto(uri);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        imagePath = getImagePath(uri, null);
        cropPhoto(uri);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO://拍照
                if (resultCode == RESULT_OK) {
                    cropPhoto(imageUri);//裁剪图片
                }
                break;
            case CHOOSE_PHOTO://打开相册
                // 判断手机系统版本号
                if (Build.VERSION.SDK_INT >= 19) {
                    Log.d("zzz", "onActivityResult: "+"4.4+");
                    // 4.4及以上系统使用这个方法处理图片
                    handleImageOnKitKat(data);
                } else {
                    Log.d("zzz", "onActivityResult: "+"4.4-");

                    // 4.4以下系统使用这个方法处理图片
                    handleImageBeforeKitKat(data);
                }
                break;
            case PICTURE_CUT://裁剪完成
                isClickCamera = true;
                Bitmap bitmap = null;
                try {
                    if (isClickCamera) {
                        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(outputUri));
                    } else {
                        bitmap = BitmapFactory.decodeFile(imagePath);
                    }

                    if (bitmap == null)
                    {
                        Log.d("zzz","为空");
                        Log.d("zzz",bitmap.toString());
                        return ;
                    }
                    else
                    {
                        userimg.setImageBitmap(bitmap);
                        Log.d("zzz","不为空");
                    }
                    Log.d("zzz","啊啊啊");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }


}
